package cn.wolfcode.luowowo.website.interceptor;

import cn.wolfcode.luowowo.cache.service.IUserRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annoation.LoginCheck;
import cn.wolfcode.luowowo.website.web.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckLoginInterceptor extends HandlerInterceptorAdapter {
    @Reference
    private IUserRedisService userRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfo userInfo = null;
        String token = CookieUtil.getToken( request, response );
        userInfo = userRedisService.getUserInfoByToken( token );
        if (handler instanceof HandlerMethod ) {
            HandlerMethod method = (HandlerMethod) handler;
            //需要登录验证
            if (method.hasMethodAnnotation( LoginCheck.class )) {
                if (token == null || userInfo == null) {
                    response.sendRedirect( "/login.html" );
                    return false;
                }
            }
        }
        //这样的话,登录了,即使访问不需要登录的页面也是会显示用户的信息
        request.getSession().setAttribute( "userInfo", userInfo );
        return true;
    }
}
